'use strict';

const { Service } = require('egg');
class borrowService extends Service {
  // 查询全部借阅记录
  async findAllBorrow() {
    const data = await this.app.model.Borrow.find({});
    return data;
  }
  // 添加借阅记录
  async addBorrow(userName, isbn) {
    const data = await this.app.model.Borrow.find({ userName, isbn });
    if (data.length === 0) {
      const model = new this.app.model.Borrow({
        userName,
        isbn,
        startTime: Date.now(), // 时间戳
      });
      await model.save();
      return { code: 200, data: model };
    } else {
      return { code: 501, data: '该用户已经借阅该图书,不可以重复借阅' };
    }
  }
  // 根据用户查询借阅记录
  async selectBorrowByUserName(userName) {
    const data = await this.app.model.Borrow.find({ userName }); // 执行mongoose的查询语句
    if (data.length === 0) {
      return { code: 501, msg: '信息为空!' };
    } else {
      return data;
    }
  }
  // 根据isbn查询借阅记录
  async selectBorrowByIsbn(isbn) {
    const data = await this.app.model.Borrow.find({ isbn }); // 执行mongoose的查询语句
    if (data.length === 0) {
      return { code: 501, msg: '信息为空!' };
    } else {
      return data;
    }
  }
  // 删除借阅记录
  async deleteBorrow(userName, isbn) {
    const data = await this.app.model.Borrow.remove({ userName, isbn });
    if (data.n >= 1) {
      return { code: 200, data };
    } else {
      return { code: 501, msg: '删除失败!' };
    }
  }
}
module.exports = borrowService;
